<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="产品代码" prop="componentsId">
            <el-select
              v-model="formData.productNo"
              clearable
              filterable
              @change="onChangeProduct($event)"
              placeholder="请选择代码"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.no"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品名称" prop="productNo">
            <el-input v-model="formData.productName" placeholder="请输入产品名称" :disabled="true"/>
            <el-input v-model="formData.productId" placeholder="请输入产品名称" :disabled="true" v-show="false"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="道具编码" prop="itemNo">
            <el-input v-model="formData.itemNo" placeholder="请输入道具编码" :disabled="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品规格" prop="dimension">
            <el-input v-model="formData.dimension" placeholder="请输入产品规格" :disabled="true"/>
          </el-form-item>
        </el-col>
<!--        <el-col :span="12">-->
<!--          <el-form-item label="单位" prop="unit">-->
<!--            <el-select v-model="formData.unit" class="w-1/1" placeholder="请选择单位" :disabled="true">-->
<!--              <el-option-->
<!--                v-for="dict in getIntDictOptions(DICT_TYPE.CRM_PRODUCT_UNIT)"-->
<!--                :key="dict.value"-->
<!--                :label="dict.label"-->
<!--                :value="dict.value"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="12">
          <el-form-item label="数量" prop="count">
            <el-input-number
              v-model="formData.count"
              controls-position="right"
              @change="onChangeCount"
              :min="0.001"
              :precision="3"
              class="!w-100%"
            />
          </el-form-item>
        </el-col>
<!--        <el-col :span="12">-->
<!--          <el-form-item label="产品价格" prop="productPrice">-->
<!--            <el-input v-model="formData.productPrice"  :disabled="true"/>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="12">
          <el-form-item label="订单售价" prop="contractPrice">
            <el-input-number
              v-model="formData.contractPrice"
              controls-position="right"
              @change="onChangePrice"
              :min="0.001"
              :precision="2"
              class="!w-100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="价税合计" prop="totalPrice">
            <el-input v-model="formData.totalPrice" placeholder="请输入价税合计" :disabled="true"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="note">
            <el-input type="textarea" v-model="formData.note" placeholder="请输入备注" :rows="3" maxlength="120"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as ProductApi from '@/api/crm/product'
import { erpPriceInputFormatter, erpPriceMultiply } from '@/utils'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import {ProductComponents, ProductComponentsApi} from "@/api/crm/productcomponents";
import * as ContractApi from "@/api/crm/contract";
import {
  ContractProductVO,
} from "@/api/crm/contract";

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  contractId: undefined,
  productId: undefined,
  productNo: undefined,
  productName: undefined,
  itemNo: undefined,
  dimension: undefined,
  unit: undefined,
  productPrice: undefined,
  contractPrice: undefined,
  totalPrice: undefined,
  count: undefined,
  note: undefined,
})
//
const formRules = reactive({
  productId: [{ required: true, message: '产品不能为空', trigger: 'blur' }],
  contractPrice: [{ required: true, message: '价格不能为空', trigger: 'blur' }],
  count: [{ required: true, message: '产品数量不能为空', trigger: 'blur' }]
})
const formRef = ref([]) // 表单 Ref
const productList = ref<ProductApi.ProductVO[]>([]) // 产品列表
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  customerId: undefined,
  productId: undefined
})// 搜索的表单

/** 监听合同产品变化，计算合同产品总价 */
// watch(
//   () => formData.value,
//   (val) => {
//     if (!val || val.length === 0) {
//       return
//     }
//     // 循环处理
//     // val.forEach((item) => {
//     //   if (item.contractPrice != null && item.count != null) {
//     //     item.totalPrice = erpPriceMultiply(item.contractPrice, item.count)
//     //   } else {
//     //     item.totalPrice = undefined
//     //   }
//     // })
//   },
//   { deep: true }
// )
/** 打开弹窗 */
const open = async (type: string, id?: number,contractId?: number) => {

  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  formData.value.contractId = contractId
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ContractApi.getContractProductInfo(id)
    } finally {
      formLoading.value = false
    }
  }
  // 查询产品下拉选
  productList.value = await ProductApi.getProductSimpleList(queryParams)

}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ContractProductVO
    if (formType.value === 'create') {
      await ContractApi.createContractProduct(data)
      message.success(t('common.createSuccess'))
    } else {
      await ContractApi.updateContractProduct(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    productId: undefined,
    productNo: undefined,
    itemNo: undefined,
    dimension: undefined,
    productPrice: undefined,
    contractPrice: undefined,
    count: undefined,
    note: undefined,
  }
  // formRef.value?.resetFields()
}

/** 处理产品变更 */
const onChangeProduct = (productId) => {
  const product = productList.value.find((item) => item.id === productId)
  if (product) {
    formData.value.unit = product.unit
    formData.value.productNo = product.no
    formData.value.productId = product.id
    formData.value.productName = product.name
    formData.value.itemNo = product.itemNo
    formData.value.productPrice = product.price
    formData.value.dimension = product.dimension
  }
  formData.value.contractPrice = undefined
  formData.value.count = undefined
  formData.value.totalPrice = undefined
}

const onChangeCount = () => {
  formData.value.totalPrice = erpPriceMultiply(formData.value.contractPrice, formData.value.count)
}

const onChangePrice = () => {
  formData.value.totalPrice = erpPriceMultiply(formData.value.contractPrice, formData.value.count)
}

/** 动态获取客户产品 */
const getProductOptions = computed(() =>{
  // if(customerId.value){
  //   return productList.value.filter((item) => item.customerId == customerId.value)
  // }else{
  // }
  return productList.value

})
/** 初始化 */
// onMounted(async () => {
//   productList.value = await ProductApi.getProductSimpleList(queryParams)
// })

</script>
